# -*- coding:utf-8 -*-
# @Time: 2020/9/2 13:50
# @Author: liupengfei
# @File: serializers.py
import datetime

from rest_framework import serializers
from .models import Coupon


class CouponSerializer(serializers.ModelSerializer):
    user = serializers.CharField(source='user.nickname', read_only=True)
    start_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    end_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = Coupon
        fields = ('id', 'status', 'title', 'money', 'total_quantity', 'issued_quantity',
                  'start_time', 'end_time', 'notes', 'user', 'status_text')

    def validate(self, attrs):
        start_time = self.initial_data['start_time']
        attrs['start_time'] = datetime.datetime.strptime(str(start_time), '%Y-%m-%d %H:%M')
        end_time = self.initial_data['end_time']
        attrs['end_time'] = datetime.datetime.strptime(str(end_time), '%Y-%m-%d %H:%M')
        if attrs['end_time'] <= attrs['start_time']:
            raise serializers.ValidationError('结束时间不能小于开始时间')
        return attrs
